package com.waibao.demo.controller;

import com.waibao.demo.entity.Homework;
import com.waibao.demo.service.HomeworkService;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * (Homework)表控制层
 *
 * @author makejava
 * @since 2020-05-27 20:16:51
 */
@RestController
@RequestMapping("homework")
public class HomeworkController {
    /**
     * 服务对象
     */
    @Resource
    private HomeworkService homeworkService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Homework selectOne(Integer id) {
        return this.homeworkService.queryById(id);
    }

    @GetMapping("Shangchuang")
    public String insertByExcel() {
        String path = System.getProperty("user.dir")+"\\17外包第6学期实训安排.xlsx";
        try {
            //引入文件并创建工作簿
            InputStream input = new FileInputStream(path);
            XSSFWorkbook read = new XSSFWorkbook(input) ;

            int sheetSize;      //excel的sheet序号

            //只上传第一个表数据
            for(sheetSize = 0 ; sheetSize < 1 ; sheetSize++){
                XSSFSheet sheet = read.getSheetAt(sheetSize);     //读取第sheetSize的表
                int row_total = sheet.getLastRowNum();            //最大行数

                int cloumn_total = sheet.getRow(0).getLastCellNum();    //读取最大列数


                Homework homework = new Homework();
                for(int row = 2; row < row_total; row++){       //去除掉无意义数据的行
                    sheet.getRow(row).getCell(0).setCellType(CellType.STRING);      //把No单元格设置为String类型
                    homework.setNo(Integer.parseInt(sheet.getRow(row).getCell(0).getStringCellValue()));
                    sheet.getRow(row).getCell(1).setCellType(CellType.STRING);      //把Sno单元格设置为String类型
                    homework.setSno(sheet.getRow(row).getCell(1).getStringCellValue());
                    homework.setName(sheet.getRow(row).getCell(2).getStringCellValue());
                    homework.setClassno(sheet.getRow(row).getCell(3).getStringCellValue());
                    homework.setRemarks(sheet.getRow(row).getCell(4).getStringCellValue());

                    homeworkService.insert(homework);

                }
                System.out.println("\n");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("input出错");
            return "false";
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("read出错");
            return "false";
        }
        return "ok";
    }


}